"""
@Project ：tds 
@File    ：demo.py
@IDE     ：PyCharm 
@Author  ：靓仔
@Date    ：2025/2/7 0007 16:48 
"""

from http.server import HTTPServer, BaseHTTPRequestHandler
import json
from urllib.parse import urlparse, parse_qs
import datetime


class RequestHandler(BaseHTTPRequestHandler):
    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()

    def do_GET(self):
        # 记录请求信息
        current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        parsed_path = urlparse(self.path)
        query_params = parse_qs(parsed_path.query)

        request_info = {
            "时间": current_time,
            "路径": parsed_path.path,
            "参数": query_params,
            "请求头": dict(self.headers)
        }

        # 将请求信息写入日志文件
        with open('request_log.txt', 'a', encoding='utf-8') as f:
            f.write(f"\n{'=' * 50}\n")
            f.write(json.dumps(request_info, ensure_ascii=False, indent=2))
            f.write("\n")

        self._set_headers()
        self.wfile.write(json.dumps({"status": "logged"}).encode())

    def do_POST(self):
        content_length = int(self.headers.get('Content-Length', 0))
        post_data = self.rfile.read(content_length)

        # 记录请求信息
        current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        parsed_path = urlparse(self.path)

        request_info = {
            "时间": current_time,
            "路径": parsed_path.path,
            "请求头": dict(self.headers),
            "请求体": post_data.decode('utf-8')
        }

        # 将请求信息写入日志文件
        with open('request_log.txt', 'a', encoding='utf-8') as f:
            f.write(f"\n{'=' * 50}\n")
            f.write(json.dumps(request_info, ensure_ascii=False, indent=2))
            f.write("\n")

        self._set_headers()
        self.wfile.write(json.dumps({"status": "logged"}).encode())


def run(port=5000):
    print(f"启动监听服务器在端口 {port}...")
    server_address = ('', port)
    httpd = HTTPServer(server_address, RequestHandler)
    print(f"服务器已启动，访问 http://localhost:{port}")
    httpd.serve_forever()


if __name__ == '__main__':
    run()